﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Blog.TemplateEngine.Helpers;

namespace Blog.TemplateEngine.Functions
{
    class NowFunction : IFunction
    {
        protected INode Compile(Parser parser, Token token)
        {
            string[] source = token.Content.SplitAndTrim(' ');
            IDictionary<string, IParameter> parameters = token.Content.ParseNamedVariables(':');
            
            return new NowNode(DateTime.Now, parameters.ContainsKey("format") ? parameters["format"] : null);
        }

        INode IFunction.Compile(Parser parser, Token token)
        {
            return Compile(parser, token);
        }
    }

    class NowNode : INode
    {
        DateTime mNow;
        IParameter mFormat;

        public NowNode(DateTime now, IParameter format)
        {
            mNow = now;
            mFormat = format;
        }

        protected string Render(Context context)
        {
            var result = new StringBuilder();

            if (mFormat == null)
            {
                result.Append(mNow.ToString());
            }
            else
            {
                result.Append(mNow.ToString(mFormat.AsString(context)));
            }

            return result.ToString();
        }

        string INode.Render(Context context)
        {
            return Render(context);
        }
    }
}
